<?php
/**
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file license.txt or that can be found at 
 * http://code.google.com/p/billboardce/wiki/License.
 *
 * @package    Slidestream_IndexController
 * @category   Controller
 * @license    http://code.google.com/p/billboardce/wiki/License New BSD License
 * @version    SVN: $Id: $
 */

/**
 * Main controller for the application
 *
 * @package    Slidestream_IndexController
 * @category   Controller
 */
class Slidestream_IndexController extends Zend_Controller_Action 
{   
          
    /**
     * Shows the slide streams that the user has created
     *
     */
    public function indexAction()
    {
        // @todo right now this lists all slides streams.  Should just list the ones the user has created
        
        $this->view->acl = array(
                               'details' => $this->_helper->hasAccess('details')
                           );
        
        $slideStream = new Slide_Stream();
        
        $this->view->slideStreams = $slideStream->fetchAll(null, 'title');
        
        $this->_helper->pageTitle('slidestream-index-index:title');
    }
    
    /**
     * Lets the user create a new slide stream
     */
    public function addAction()
    {
        $slideStream = new Slide_Stream();
        
        $messages = array();
        
        $form = $slideStream->form();
                
        $data = array(
                    'title' => 'Untitled'
                );
        
        $slideStreamId = $slideStream->insert($data);
                
        $this->_helper->redirector->gotoUrl('/slidestream/index/details?slideStreamId=' . $slideStreamId);
    }
    
    /**
     * The main slide stream editor.  This is the bee's knees!
     */
    public function detailsAction()
    {
        $get = Zend_Registry::get('getFilter');
        
        if (!isset($get->slideStreamId)) {
            throw new Ot_Exception_Input('No slide steram ID given');
        }
        
        $slideStreamId = $get->slideStreamId;
        
        $slideStream = new Slide_Stream();
        
        $thisSlideStream = $slideStream->find($slideStreamId);
        
        if (is_null($thisSlideStream)) {
            throw new Ot_Exception_Data('Slide Stream not found');
        }
        
        $this->view->slideStream = $thisSlideStream;
        
        $slideStreamMap = new Slide_Stream_Map();
        
        $om = new Option_Module();
        $optionModules = $om->getEnabledModules('slide');
        
        $this->view->optionModules = $optionModules;
        
        $this->view->messages = $this->_helper->flashMessenger->getMessages();
        $this->view->headScript()->appendFile($this->view->baseUrl() . '/public/scripts/jquery.plugin.form.js');
        $this->view->headScript()->appendFile($this->view->baseUrl() . '/public/scripts/jquery.plugin.json.js');
    }
    
    /**
     * Saves the structure for the slide stream
     */
    public function saveSlideStreamAction()
    {
        $post = Zend_Registry::get('postFilter');
        
        $data = Zend_Json::decode($_POST['data']);
        $slideStreamId = $post->slideStreamId;
        
        $slideStreamMap = new Slide_Stream_Map();
        
        $this->_helper->viewRenderer->setNeverRender();
        $this->_helper->layout()->disableLayout();
        
        try {
            $slideStreamMap->saveSlideStream($slideStreamId, $data);
        } catch (Exception $e) {
            echo Zend_Json::encode(array('rc' => 0, 'msg' => $e->getMessage()));
            return;
        }
                
        echo Zend_Json::encode(array('rc' => 1, 'msg' => 'Slide stream saved successfully!'));
    }
    
    /**
     * Saves the data for the slidestream object from the ajax request
     */
    public function saveSlideStreamInfoAction()
    {
        $post = Zend_Registry::get('postFilter');
        
        $slideStream = new Slide_Stream();
        
        if (!isset($post->slideStreamId)) {
            throw new Ot_Exception_Input('No slide stream ID provided');
        }
        
        $this->_helper->viewRenderer->setNeverRender();
        $this->_helper->layout()->disableLayout();
        
        $data = array(
                    'slideStreamId' => $post->slideStreamId,
                    'title'         => $post->title
        );
        
        try {
            $slideStream->update($data, null);
        } catch (Exception $e) {
            echo Zend_Json::encode(array('rc' => 0, 'msg' => $e->getMessage()));
            return;
        }
                
        echo Zend_Json::encode(array('rc' => 1, 'msg' => 'Slide stream info saved successfully!'));
    }
    
    /**
     * Deletes a slide from the slideStream
     */
    public function deleteSlideAction()
    {
        $post = Zend_Registry::get('postFilter');
        
        if (!isset($post->slideStreamId)) {
            throw new Ot_Exception_Input('No slidestream ID provided');
        }
        
        if (!isset($post->slideId)) {
            throw new Ot_Exception_Input('No slide ID provided');
        }
        
        $slideStreamMap = new Slide_Stream_Map();
        
        $where = $slideStreamMap->getAdapter()->quoteInto('slideStreamId = ?', $post->slideStreamId)
               . ' AND '
               . $slideStreamMap->getAdapter()->quoteInto('entityType = ?', 'slide') // @todo this will need to be changed to support slidestreams as well later
               . ' AND '
               . $slideStreamMap->getAdapter()->quoteInto('entityTypeId = ?', $post->slideId);
        
        $this->_helper->viewRenderer->setNeverRender();
        $this->_helper->layout()->disableLayout();
        
        try {
            $slideStreamMap->delete($where);   
        } catch (Exception $e) {
            echo Zend_Json::encode(array('rc' => 0, 'msg' => $e->getMessage()));
            return;
        }
        
        echo Zend_Json::encode(array('rc' => 1, 'msg' => 'Slide successfully deleted'));
    }
    
    /**
     * Returns the entities in a slidestream as JSON
     */
    public function getEntitiesAction()
    {
        $get = Zend_Registry::get('getFilter');
        
        if (!isset($get->slideStreamId)) {
            throw new Ot_Exception_Input('No slide steram ID given');
        }
        
        $slideStreamId = $get->slideStreamId;
        
        $slideStreamMap = new Slide_Stream_Map();
        
        $entities = $slideStreamMap->getEntitiesForSlideStream($slideStreamId);
        
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNeverRender();
        
        echo Zend_Json::encode($entities);
    }
    
    public function generateScreenshotsAction()
    {
        $get = Zend_Registry::get('getFilter');
        
        if (!isset($get->slideId)) {
            throw new Exception('Slide ID not set in query string');
        }
        
        $slide = new Slide();
        
        $thisSlide = $slide->find($get->slideId);
        if (is_null($thisSlide)) {
            throw new Exception('Slide not found');
        }
        
        $screenshotPath = realpath(APPLICATION_PATH . '/../public/screenshots');

        $screenshot = new Screenshot();
        
        if (!is_dir($screenshotPath . '/' . $get->slideId)) {
            mkdir($screenshotPath . '/' . $get->slideId);
        }
        
        $sourceImage    = $screenshotPath . '/' . $get->slideId . '/source.jpg';
        $previewImage   = $screenshotPath . '/' . $get->slideId . '/preview.jpg';
        $thumbnailImage = $screenshotPath . '/' . $get->slideId . '/thumbnail.jpg';
        
        // capture largest screenshot
        if (!(file_exists($sourceImage))) {

            $source = $screenshot->capture($thisSlide->url, 300, 250);
            
            if (!is_null($source)) {
                file_put_contents($sourceImage, $source);
                file_put_contents($previewImage, $source);
                
                $image = imagecreatefromjpeg($sourceImage);
                $dst = imagecreatetruecolor(150, 100);
    
                // copy resized image to new canvas
                imagecopyresampled($dst, $image, 0, 0, 0, 0, 150, 100, 300, 250);  
                            
                imagejpeg($dst, $thumbnailImage, 100);
            }
        }
        
        die();
    }
    
    public function screenshotsExistAction()
    {
    	
        $get = Zend_Registry::get('getFilter');
        
        if (!isset($get->slideId)) {
            throw new Exception('Slide ID not set in query string');
        }
        
        $slide = new Slide();
        
        $thisSlide = $slide->find($get->slideId);
        if (is_null($thisSlide)) {
            throw new Exception('Slide not found');
        }
        
        $screenshotPath = realpath(APPLICATION_PATH . '/../public/screenshots');
        
        if (!is_dir($screenshotPath . '/' . $get->slideId)) {
            mkdir($screenshotPath . '/' . $get->slideId);
        }
        
        $sourceImage    = $screenshotPath . '/' . $get->slideId . '/source.jpg';
        
        // check to see if source exists.  if it does, so should the others
        if ((file_exists($sourceImage))) {
            echo Zend_Json::encode(array('result' => '1'));
        } else {
        	echo Zend_Json::encode(array('result' => '0'));
        }
        
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNeverRender();
    }
}